package com.iqiyi.pps.epg.core.service.task;

import com.iqiyi.pps.epg.core.dao.task.SimpleTaskDao;
import com.iqiyi.pps.epg.core.model.task.SimpleTask;
import com.iqiyi.pps.epg.core.utils.RequestUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2015/12/23.
 */
@Service
@Transactional
public class SimpleTaskServiceImpl implements SimpleTaskService {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SimpleTaskServiceImpl.class);
    @Autowired
    private SimpleTaskDao simpleTaskDao;


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<SimpleTask> findList(int taskType, int taskStatus) {
        List<Criterion> list = new ArrayList<Criterion>();
        list.add(Restrictions.eq("taskStatus", taskStatus));

        list.add(Restrictions.eq("workIp", RequestUtils.getLoadlIpByOS()));
        list.add(Restrictions.eq("taskType", taskType));
        List<SimpleTask> resultList = null;
        try {
            Criteria criteria = simpleTaskDao.createCriteria();
            for (Criterion c : list) {
                criteria.add(c);
            }
            criteria.setMaxResults(1400);
            criteria.addOrder(Order.asc("createTime"));
            resultList = simpleTaskDao.find(criteria);
        } catch (Exception e) {
            logger.error("[SimpleTaskDao] exception={}",e);
        }
        return resultList;
    }

    @Override
    public void batchUpdateList(List<SimpleTask> list) {
        try {
            for (SimpleTask simpleTask : list) {
                simpleTaskDao.save(simpleTask);
            }
        } catch (Exception e) {
            logger.error("[SimpleTaskDao] exception={}",e);
        }
    }

    @Override
    public SimpleTask findById(long id){
        return simpleTaskDao.findUniqueBy("id",id);
    }

    @Override
    public void saveTask(SimpleTask task) {
        simpleTaskDao.save(task);
    }
    @Override
    public int  interruptTask(long entityId , int taskType){
        int executeUpdateNum = 0;
        String hql ="update SimpleTask set taskStatus = -100 where taskStatus = 0 and entityId = ? and taskType = ?";
        executeUpdateNum = simpleTaskDao.createQuery(hql).setLong(0,entityId).setInteger(1,taskType).executeUpdate();
        return executeUpdateNum;
    }
}
